<!-- 体检项目组合页面  zxy-2022-12-20 -->
<script setup lang='ts' name="ProjectPortfolio">
import {onBeforeMount, ref, reactive, watch} from 'vue'
import {ElMessage, ElMessageBox, FormRules} from 'element-plus'
import dayjs from 'dayjs'

import {HeaderData} from '@/components/dTable/dTable'
import {FromItem} from '@/components/dFrom/dFrom'
import pageContainer from '@/components/pageContainer.vue'
import dTable from '@/components/dTable/dTable.vue'
import dFrom from '@/components/dFrom/dFrom.vue'

import {
  getInstrumentListReq, getInfoByBarcodeReq, getSignedListReq, saveInstrumentItemReq, getSelectMaxSampleNoReq, deleteInstrumentItemReq,
  Instrument, FromData, PhysicalItem, SignedItem
} from '@/api/examinationManager/specimen'

import { getObjectByKey, PositiveInteger, disabledAfterDate} from '@/util/common'

import useUser from '@/store/user'
const user = useUser.setup().store

//当前页面 表格数据 定义
const tableData = ref<Array<PhysicalItem>>([])
const tableData2 = ref<Array<SignedItem>>([])

//显示加载状态
const showLoading = ref(false)

//表格头部数据定义
const tableHeaderData = ref<Array<HeaderData>>([
  {prop:'enShortName', label:'项目英文简称', columnType:'text', align:'left', 'min-width':'100'},
  {prop:'itemName', label:'项目名称', columnType:'text', align:'left', 'min-width':'100'}
])
//表格头部数据定义
const tableHeaderData2 = ref<Array<HeaderData>>([
  {prop:'sampleNo', label:'标本号', columnType:'text', align:'left', 'min-width':'100'},
  {prop:'checkupNo', label:'体检号', columnType:'text', align:'left', 'min-width':'100'},
  {prop:'personName', label:'姓名', columnType:'text', align:'left', 'min-width':'100'},
  {prop:'gender', label:'性别', columnType:'text', align:'left', 'min-width':'100'},
  {prop:'age', label:'年龄', columnType:'text', align:'left', 'min-width':'100'},
  {prop:'sampleTypeName', label:'标本类型', columnType:'text', align:'left', 'min-width':'100'}
])

//表单定义
const formItems = ref<Array<FromItem>>([
  {label:'检验仪器', placeholder:'请输入检验仪器', prop:'instrumentId', type:'selete', seleteData:[], notClearable:true},
  {label:'检验日期', placeholder:'请输入检验日期', prop:'inspectTime', type:'antdDate', dateFormat:'YYYY-MM-DD', notClearable:true, disabledDate:disabledAfterDate},
  {label:'条形码', placeholder:'请输入或扫描条形码', prop:'barcode', type:'slot', slotName:'barcode'   },
  {label:'标本号', placeholder:'请输入标本号', prop:'sampleNo', type:'input' },
  {label:'体检号', placeholder:'', prop:'checkupNo', type:'input', disabled:true},
  {label:'姓名', placeholder:'', prop:'personName', type:'input', disabled:true},
  {label:'性别', placeholder:'', prop:'gender', type:'input', disabled:true},
  {label:'年龄', placeholder:'', prop:'age', type:'input', disabled:true},
  {label:'送检日期', placeholder:'请选择送检日期', prop:'sendTime', type:'antdDate', dateFormat:'YYYY-MM-DD', notClearable:true, disabledDate:disabledAfterDate},
  {label:'送检医师', placeholder:'', prop:'sendDoctorName', type:'input', disabled:true}
  // {label:'送检医师', placeholder:'', prop:'sendDoctorId', type:'input', disabled:true}
])
const formRules = reactive<FormRules>({
  sampleNo:[
    {required:true, message:'请输入正整数', pattern:PositiveInteger,  trigger: ['change', 'blur']},
    {message:'长度不应超过5个字符',  max:5, trigger: ['change', 'blur']}
  ],
  barcode:[
    {required:true, message:'请输入或扫描条形码', trigger: ['change', 'blur']}
  ]
})

//表单初始数据
const formDataBase = {
  instrumentId:'', //仪器id
  sampleNo:'', //标本号
  barcode:'', //条码号 A0012301160006
  inspectTime:dayjs(new Date()).format('YYYY-MM-DD'), //检验时间
  sendTime:dayjs(new Date()).format('YYYY-MM-DD'), //送检时间
  sendDoctorId:user.userInfor?.id,
  sendDoctorName:user.userInfor?.userName //送检医生姓名
}

//表单数据
const formData = ref<FromData>({
  ...formDataBase
})

//获取仪器列表
const instrumentList = ref<Array<Instrument>>([])

//当前选中的仪器的体检项目
const currInstrumentItems = ref<Array<PhysicalItem>>([])

//获取仪器列表及体检项目列表
const getInstrumentList = () => {
  getInstrumentListReq().then(res => {
    const {data} = res.data

    instrumentList.value = data //所有仪器
    formData.value.instrumentId = data[0]?.id //选中第一个
    // currInstrumentItems.value = data[0]?.itemVOS || [] //选中的仪器的项目列表

    const item = getObjectByKey(formItems.value, 'prop', 'instrumentId') //仪器下拉列表
    if (item && item.type === 'selete') {
      item.seleteData = data?.map(item => {
        return {
          label:item.instrumentName,
          value:item.id
        }
      })
    }
  })
}

//获取已登记列表
const getSignedList = () => {
  showLoading.value = true
  if (!formData.value.instrumentId) return
  getSignedListReq({
    instrumentId:formData.value.instrumentId,
    startInspectTime:formData.value.inspectTime + ' 00:00:00',
    endInspectTime:formData.value.inspectTime + ' 23:59:59'
  }).then(res => {
    tableData2.value = res.data.data || []
    showLoading.value = false
  }).catch((error) => {
    showLoading.value = false
    console.warn(error)
  })
}

//获取最大标本号
const getSelectMaxSampleNo = () => {
  if (!formData.value.instrumentId) return
  getSelectMaxSampleNoReq({
    instrumentId:formData.value.instrumentId,
    startInspectTime:formData.value.inspectTime + ' 00:00:00',
    endInspectTime:formData.value.inspectTime + ' 23:59:59'
  }).then(res => {
    formData.value.sampleNo = '' + (res.data.data ? res.data.data : 1)
  })
}

//表单清除控制
const resetFieldsFlag = ref(false)

//触发验证
const validateFlag = ref(false)

// 确认按钮
const onConfirm = () => {
  validateFlag.value = !validateFlag.value
}

//提交事件
const onSubmit = () => {
  saveInstrumentItemReq({
    ...formData.value,
    inspectTime:formData.value.inspectTime + ' 00:00:00',
    sendTime:formData.value.sendTime + ' 00:00:00'
  }).then(() => {
    ElMessage.success('登记成功')
    getSignedList()

    resetFieldsFlag.value = !resetFieldsFlag.value //去除校验信息
    const {sampleNo, instrumentId, inspectTime, sendTime} = formData.value
    formData.value = {
      ...formDataBase,
      sampleNo:'' + (sampleNo ? parseInt(sampleNo) + 1 : 1),
      instrumentId,
      inspectTime,
      sendTime
    }
  })
}

//自动确认按钮是否勾选
const autoConfirm = ref(false)

//条码变化时查询条码详细信息并回显，如果勾选了自动确认，查询到信息后自动提交
// watch(
//   () => formData.value.barcode,
//   (newValue) => {
const barcodeEnter = () => {
  const newValue = formData.value.barcode
  if (!newValue) {
    formData.value = {...formData.value, checkupNo:'', personName:'', gender:'', age:undefined}
    return
  }
  tableData.value = []
  getInfoByBarcodeReq({
    barcode:newValue,
    instrumentId:formData.value.instrumentId
  }).then(res => {
    const {checkupNo, personName, gender, age, registerItemVOS} = res.data.data
    formData.value = {...formData.value, checkupNo, personName, gender, age}
    tableData.value = registerItemVOS//currInstrumentItems.value
    if (autoConfirm.value) {
      onConfirm()
    }
  }).catch(() => {
    formData.value = {...formData.value, checkupNo:'', personName:'', gender:'', age:undefined}
  })
}
//   }
// )

//检验仪器变化时获取最大标本号、已登记列表、体检项目列表
watch(
  () => formData.value.instrumentId,
  (newValue) => {
    const tempData = instrumentList.value.find(item => item.id === newValue)
    if (tempData) {
      // currInstrumentItems.value = tempData.itemVOS || []

      const { instrumentId, inspectTime, sendTime} = formData.value
      formData.value = {...formDataBase, instrumentId, inspectTime, sendTime}

      getSelectMaxSampleNo()
      getSignedList()
    }

  }, {
    immediate:true
  }
)

//检验时间变化时获取最大标本号和已登记列表
watch(
  () => formData.value.inspectTime,
  () => {
    if (!formData.value.instrumentId) {
      return
    }
    getSelectMaxSampleNo()
    getSignedList()
  }, {
    immediate:true
  }
)

//获取选择的标本id
const selectedIds = ref([])
const onMultipleSelection = (rows) => {
  selectedIds.value = rows.map(item => item.id)
}

//删除已登记标本
const deleteInstrumentItem = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.error('请选择标本')
    return
  }
  ElMessageBox.confirm(
    '是否确认删除此标本？',
    '删除确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      return deleteInstrumentItemReq(selectedIds.value)
    }).then(() => {
      ElMessage.success('删除成功')
      getSignedList()
    }).catch((error) => {
      console.warn(error)
    })
}

//DOM即将挂载
onBeforeMount(() => {
  getInstrumentList()
})
</script>

<template>
  <page-container>
    <div class="main">
      <div class="left">
        <div class="title">
          标本采录
        </div>
        <d-from
          label-position="right"
          method="post"
          :reset-fields-flag="resetFieldsFlag"
          :validate-flag="validateFlag"
          :rules="formRules"
          :form-data="formData"
          :form-items="formItems"
          :form-line-num="1"
          @submit="onSubmit"
        >
          <template #barcode>
            <el-input v-model="formData.barcode" placeholder="请输入或扫描条形码" @keyup.enter="barcodeEnter" @blur="barcodeEnter" />
          </template>
        </d-from>
        <div class="buttons">
          <el-button type="primary" @click="onConfirm">
            确认
          </el-button>
          <el-checkbox v-model="autoConfirm">
            自动
          </el-checkbox>
        </div>
      </div>
      <div class="middle">
        <div class="title">
          体检项目
        </div>
        <d-table
          :table-header-data="tableHeaderData"
          :table-data="tableData"
        />
      </div>
      <div class="right">
        <div class="title">
          已登记人员
        </div>
        <d-table
          :table-header-data="tableHeaderData2"
          :table-data="tableData2"
          :show-selection="true"
          :show-loading="showLoading"
          @multiple-selection="onMultipleSelection"
        />
        <div class="buttons">
          <el-button type="danger" plain @click="deleteInstrumentItem">
            删除标本
          </el-button>
        </div>
      </div>
    </div>
  </page-container>
</template>

<style scoped lang="less">
.main{
  display: flex;
  height:100%;
  .title{
    font-weight: bold;
    margin-bottom: 16px;
  }
  .left{
    width:275px;
    height:500px;
    flex-shrink: 0;
    .buttons{
      display: flex;
      justify-content: center;
      .el-checkbox{
        margin-left: 12px;
      }
    }
  }
  .middle{
    flex:1;
    height:100%;
    display: flex;
    flex-direction: column;
    margin: 0 15px;
    padding-left: 15px;
    border-left:6px solid #F2F2F2;
  }
  .right{
    flex: 2;
    height: 100%;
    display: flex;
    flex-direction: column;
    .buttons{
      margin-top: 16px;
      text-align: center;
    }
  }
}
</style>